﻿/// <reference path = "Base.ts" />
namespace VantCellTypes {

    interface ImageItem {
        value: string;
        image: { Name: string };
    }

    interface SwipeCellTypeParam {
        preview: boolean;
        ClickCommand: Forguncy.Plugin.ICustomCommandObject;
        useBinding: boolean;
        bindingOptions: any;
        imageItems: ImageItem[];
        vertical: boolean;
        autoplay: number;
        showIndicators: boolean;
        indicatorColor: string;
        loop: boolean;
        touchable: boolean;
    }

    export class SwipeCellType extends VantCellTypeBase<SwipeCellTypeParam> {
        public onPageLoaded(info: Forguncy.Plugin.CellTypeInfo) {
            const self = this;
            const cellType = this.cellType;
            const option = {
                template: `
<van-swipe
    ref="van-swipe"
    :vertical="vertical"
    :autoplay="autoplay"
    :show-indicators="showIndicators"
    :indicator-color="indicatorColor"
    :loop="loop"
    :touchable="touchable"
    class="fgc-media-swiper"
>
    <van-swipe-item
        :ref="'swipe-item' + index"
        :key="item.src"
        v-for="(item, index) in items"
        @click="onSwipeItemClick($event, index, item.value)"
    >
        <div class="van-image van-image-preview__image" style="transition-duration: 0.3s;height:100%;">
            <img @load="onImageLoad($event, index, item.value)" :src="item.src" class="van-image__img" style="object-fit: contain;" />
        </div>
    </van-swipe-item>
</van-swipe>
`,
                data() {
                    return {
                        items: [],
                        vertical: !!cellType.vertical,
                        autoplay: cellType.autoplay ?? undefined,
                        showIndicators: !!cellType.showIndicators,
                        indicatorColor: Forguncy.ConvertToCssColor(cellType.indicatorColor),
                        loop: !!cellType.loop,
                        touchable: !!cellType.touchable
                    };
                },
                methods: {
                    onSwipeItemClick(e, index: number, value: string) {
                        if (cellType.preview) {
                            const uniqueClass = "image-preview" + self.uId;
                            window.vant.ImagePreview({
                                images: this.items.map(item => item.src),
                                startPosition: index,
                                closeable: true,
                                className: uniqueClass
                            });
                            this.$nextTick(() => {
                                const previewItems = $(`.${uniqueClass}`).find(".van-swipe-item");
                                this.items.forEach((item, idx: number) => {
                                    self.InsertPreviewItemTemplate(previewItems[idx], item.value);
                                });
                            });
                            
                        } else {
                            if (cellType.ClickCommand?.Commands?.length) {
                                const initValue = {};
                                initValue[cellType.ClickCommand.ParamProperties["value"]] = value;
                                self.executeCustomCommandObject(cellType.ClickCommand, initValue);
                            }
                        }
                    },
                    onImageLoad(e, index: number, value: string | number) {
                        const swipeItems = $(".van-swipe-item", self.container);
                        self.InsertSwipeItemTemplate(swipeItems[index], value);
                    },
                    
                }
            };

            this.createVueApp(option);

            if (cellType.useBinding) {
                SupportDataSourceCellType.refreshData(this, cellType.bindingOptions, dataSource => {
                    if (dataSource !== null) {
                        dataSource.forEach(({ value, image }) => {
                            if (typeof image === "string") {
                                image?.split("|").forEach((fileName: string) => {
                                    if (fileName) {
                                        this.vue.items.push({
                                            value,
                                            src: this.GetBindImagePath(fileName)
                                        });
                                    }
                                });
                            }
                        });
                    }
                });
            } else {
                this.vue.items = cellType.imageItems.map(({ value, image }) => {
                    const imageItem = {
                        value,
                        src: ""
                    };
                    IconHelper.getIcon(<Icon>image, (url) => {
                        imageItem.src = url;
                    });
                    return imageItem;
                });
            }
            super.onPageLoaded(info);
        }

        public GetBindImagePath(image: string): string {
            if (image) {
                //Support external image source.
                if (image.indexOf("http://") === 0 || image.indexOf("https://") === 0) {
                    return image;
                }

                //IE 11 does not support startswith function.
                if (image.indexOf("data:image/png;base64") === 0) {
                    return image;
                }

                return Forguncy.Helper.SpecialPath.getUploadImageFolderPathInServer() + encodeURIComponent(image);
            }
            return null;
        }

        // runtime methods
        public SwitchToPrev() {
            this.vue.$refs["van-swipe"].prev();
        }

        public SwitchToNext() {
            this.vue.$refs["van-swipe"].next();
        }

        public SwitchTo(number: number) {
            const index = Number(number) - 1;
            this.vue.$refs["van-swipe"].swipeTo(index);
        }

        // video display interface
        public InsertSwipeItemTemplate(el, ID: string | number) {
            const func = this.getCustomFeatureByPath(FeaturePath.swipeItem);
            return func && func(el, ID);
        }

        public InsertPreviewItemTemplate(el, ID: string | number) {
            const func = this.getCustomFeatureByPath(FeaturePath.swipePreviewItem);
            return func && func(el, ID);
        }
    }
}

Forguncy.Plugin.CellTypeHelper.registerCellType("Vant.CellTypes.Swipe, Vant", VantCellTypes.SwipeCellType);